<template>
  <div class="customer-container" :class="rootElementClassNames" v-loading.fullscreen.lock="loadingPage" >
    <form @submit.prevent="submit" class="base-form" v-if="init" novalidate>
      <div class="fe-page-header">
        <div class="fe-page-header__left">
          {{ isEdit ? $t('common.pageTitle.pageCustomerRegisterEdit') : $t('common.pageTitle.pageCreateCustomer') }}
        </div>
        <div class="fe-page-header__right">
          <propaganda-page :propagandaData="customerSynchronization" v-if="!isOpenSystemIntegrationGray"></propaganda-page>
          <FormCellChange class="mar-r-8" :count="formCellCount" @update="(e)=>{formCellCount=e}"></FormCellChange>
          <el-button class="fe-page-header__button" type="plain-third" @click="goBack">
            {{$t('common.base.cancel')}}
          </el-button>
          <el-button
            class="fe-page-header__button"
            type="primary"
            native-type="submit"
            :disabled="submitting || pending">
            {{$t('common.base.save')}}
          </el-button>
        </div>
      </div>

      <div class="form-builder-container" :class="[formCellCount>1? 'form-builder-container-cell' : '']">
        <customer-edit-form :id="form.id" :is-create="isCreate" :fields="fields" v-model="form" ref="form" :form-cell-count="formCellCount" />
      </div>
    </form>
  </div>
</template>

<script>
/* api */
import * as CustomerApi from '@src/api/CustomerApi.ts'
/* component */
import CustomerEditForm from '@src/modules/customer/components/CustomerEditForm.vue'
import PropagandaPage from '@src/component/compomentV2/PropagandaPage';
import FormCellChange from '@src/component/compomentV2/FormCellChange';
/* enum */
import TenantDataLimitSourceEnum from '@model/enum/TenantDataLimitSourceEnum'
import TenantDataLimitTypeEnum from '@model/enum/TenantDataLimitTypeEnum'
/* util */
import platform from '@src/platform'
import * as FormUtil from '@src/component/form/util'
import * as util from '@src/modules/customer/util/customer'
/* mixin */
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import { ConnectorModuleConnectorCreateCustomerMixin } from '@src/modules/connector/mixin'
/* util */
import { parse } from '@src/util/querystring';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()
import { scrollIntoFirstRequireDom } from '@src/util/dom';
import { customerSynchronization } from '@model/enum/PropaganPageEnum'
import { getRootWindow } from '@src/util/dom'

let query;

function duibi (registerRes, obj){
  function fuzhi(a, b){
    if(b){
      if(!obj[a])
        obj[a] = {}
      obj[a][b] = registerRes[a][b]
    }
    obj[a] = registerRes[a]
  }
  for(let i in registerRes){
    if(registerRes[i] instanceof Object){ // 对象
      let attribute = registerRes[i]
      for(let ii in attribute){
        if(attribute[ii] instanceof Array){ // 数组并且有值
          if(attribute[ii].length){
            fuzhi(i, ii)
          }
        }else{ // 除了数组和对象之外的
          if(attribute[ii])
            fuzhi(i, ii)
        }
      }
    }else{
      if(registerRes[i] instanceof Array){ // 数组并且有值
        if(registerRes[i].length){
          fuzhi(i)
        }
      }else{ // 除了数组和对象之外的
        if(registerRes[i])
          fuzhi(i)
      }
    }
  }
  return obj
}
export default {
  name: 'CustomerEditView',
  inject: ['initData'],
  mixins: [VersionMixin, ThemeMixin, ConnectorModuleConnectorCreateCustomerMixin],
  provide() {
    return {
      // 客户是否编辑
      isEdit: this.isEdit
    }
  },
  data() {
    
    return {
      submitting: false,
      pending: false,
      loadingPage: false,
      form: {},
      init: false,
      auth: {},
      fieldInfo: [],
      customerSynchronization,
      formCellCount:1,
    }
  },
  computed: {
    action() {
      return this.initData.action
    },
    editId() {
      return this.initData.id || ''
    },
    registerId() {
      // const matchRes = window.location.href.match(/customer\/product\/edit\/([\w-]*)(\??.*)/);
      return this.initData.registerId || '';
    },
    eventId() {
      return this.initData.eventId || ''
    },
    fields() {
      let originFields = this.fieldInfo || []
      let sortedFields = originFields
        .sort((a, b) => a.orderId - b.orderId)
        .map(f => {
          if (f.formType === 'address' && f.isSystem) {
            f.isNull = this.initData.isAddressAllowNull ? 1 : 0
          }
          // 客户名称长度单独处理
          if (f.fieldName === 'name') {
            f.maxlength = 50
          }// 客户名称长度单独处理
          if (['lmPhone', 'lmEmail'].includes(f.fieldName)) {
            f.isNullRelationFields = originFields.filter(field => 
              ['lmPhone', 'lmEmail'].includes(field.fieldName)
            )
          }
          return f
        })
        .filter(f => {
          return (
            f.fieldName !== 'tags'
            || (f.fieldName === 'tags' && this.initData.isDivideByTag)
          )
        })
      return FormUtil.migration(sortedFields)
    },
    isCreate() {
      return this.action == 'create'
    },
    isEdit() {
      return !this.isCreate && this.editId
    },
    // 是否开启系统集成灰度
    isOpenSystemIntegrationGray() {
      const RootWindow = getRootWindow(window);
      return Boolean(RootWindow?.grayAuth?.THIRD_APP);
    }
  },
  methods: {
    goBack() {
      
      try {
        
        const isInFrame = this.validateCurrentWindowIsInFrame()
        
        if (isInFrame) {
          this.postCloseDialogMessage()
          return
        }
        
      } catch (error) {
        console.error(error)
      }
      let fromid = window.frameElement.getAttribute('fromid');
      if (!fromid || this.action == 'create') {
        let id = window.frameElement.dataset.id
        return this.$platform.closeTab(id)
      }
      parent.frameHistoryBack(window)
    },
    submit() {
      this.submitting = true
      this.$refs.form
        .validate()
        .then(valid => {
          scrollIntoFirstRequireDom(this.$refs.form.$refs.form)
          this.submitting = false
          if (!valid) return Promise.reject('validate fail.')

          const submitForm = disposeFormSubmitTime(this.fields, this.form) // 处理国际化日期时间数据转换
          
          let params = util.packToCustomer(
            this.fields,
            submitForm,
            this.initData.tags
          )
          
          params = this.globalFormSubmissionDataProcessingHandler(this.fields, params)
          
          // IM创建客户带conversationId 
          if(query.conversationId ) {
            params.conversationId = +query.conversationId 
          }

          // 门户数据看板创建客户带 bizTypeModule & bizTypeId
          if(query.bizTypeId) {
            params.bizTypeModule = query.bizTypeModule 
            params.bizTypeId = query.bizTypeId 
          }

          this.registerId && (params.registerId = this.registerId)
          this.toggleLoading()

          if (this.action == 'edit' && this.$refs.form?.needServerDeleFiles?.length) {
            params['deleteFiles'] = this.$refs.form?.needServerDeleFiles
          }
          
          if (this.action === 'edit') {
            return this.updateMethod(params)
          }
          if (this.action === 'createFromEvent') {
            return this.createCustomerForEvent(params)
          }

          this.createMethod(params)
        })
        .catch(err => {
          console.error(err)
          this.toggleLoading(false)
        })
    },
    createCustomerForEvent(params) {
      this.$http.post('/event/customer/create', params)
        .then(res => {
          let isSucc = res.succ

          platform.notification({
            type: isSucc ? 'success' : 'error',
            title: isSucc ? this.$t('customer.edit.createdSuccess') : this.$t('customer.edit.createdFail'),
            message: !isSucc && res.message
          })
          
          if (!isSucc) return
          
          const params = {
            ...res.data,
            eventId: this.eventId
          }
          
          delete params.latitude
          delete params.longitude
          
          this.$http.post('/event/update4CusInfo', params, false).then(res => {
            if (this.initData.goto === 'eventView') {
              return (window.location.href = `${this.$resourcePrefix}/event/view/${this.initData.eventId}`)
            }
            if (this.initData.goto === 'createTask') {
              return (window.location.href = `${this.$resourcePrefix}/event/convent2Task/jump?eventId=${this.initData.eventId}&flow=${this.initData.flow}`)
            }
          })
          
        })
        .catch(error =>
          console.error('edit CustomerEditView createCustomerForEvent error', error)
        )
        .finally(() => {
          this.toggleLoading(false)
        })
    },
    createMethod(params) {
      
      try {
        this.setConnectorParamsForSubmit(params)
      } catch (error) {
        console.error(error)
      }
      
      const CreateCustomerPromise = this.$http.post('/customer/create', params)
      
      this.checkNumExceedLimitAfterHandler(CreateCustomerPromise)
        .then(res =>{
          let isSuccess = Boolean(res.succ)
          
          platform.notification({
            type: isSuccess ? 'success' : 'error',
            title: isSuccess ? this.$t('customer.edit.createdSuccess') : this.$t('customer.edit.createdFail'),
            message: !isSuccess && res.message
          })
          
          if (!isSuccess) return

          if (this.$route.query?.from === 'paas') {
            let paasParams = [
              {
                id: res.data.customerId, // 客户id
                name: params.name // 客户名称
              }
            ]
            let message = {
                action: 'shb.create.customer',
                data: paasParams,
                fromId: window.frameElement.getAttribute('fromid')
            };
            window.parent.postMessage(message, '*')
            let id = window.frameElement.dataset.id;
            this.$platform.closeTab(id);
          } else {
            let fromId = window.frameElement.getAttribute('fromid')
            this.$platform.refreshTab(fromId)
            this.closeAndOpenTab(res.data.customerId)
          }
          this.removeConnectorCreateSessionData()
        })
        .catch(err => {
          console.error('err', err)
        })
        .finally(() => {
          this.toggleLoading(false)
        })
    },
    changeCurrTitle (title) {
      // 跳转之前 修改tab标题
      let currTabId = window.frameElement.dataset.id;
      platform.setTabTitle({
        id: currTabId,
        title
      })
    },
    updateMethod(params) {
      const remindCount = localStorage.getItem('customer_remind_count');
      params.attribute.remindCount = remindCount || 0;

      const UpdateCustomerPromise = this.$http.post(`/customer/update?id=${this.editId}`, params)

      this.checkNumExceedLimitAfterHandler(UpdateCustomerPromise)
        .then(res => {
          if (!res.succ) {
            return platform.notification({
              type: 'error',
              title: this.$t('customer.edit.updateFail'),
              message: res.message
            })
          }

          // let fromId = window.frameElement.getAttribute('fromid')
          // this.$platform.refreshTab(fromId)
          this.reloadTab()

          // 跳转之前 修改tab标题
          this.changeCurrTitle(this.$t('customer.customerInfo'))

          window.location.href = `${this.$resourcePrefix}/customer/view/${res.data || this.editId}`
          // this.createCustomerTab(res.data || this.editId)
          // let id = window.frameElement.dataset.id;
          // this.$platform.closeTab(id);
        })
        .catch(err => {
          console.error('CustomerEditView ~ updateMethod ~ error', err)
        })
        .finally(() => {
          this.toggleLoading(false)
        })
    },
    createCustomerTab(customerId) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
    },
    reloadTab() {
      let fromId = window.frameElement.getAttribute('fromid')
      this.$platform.refreshTab(fromId)
    },
    toggleLoading(loading = true) {
      this.pending = loading
      this.loadingPage = loading
    },

    closeAndOpenTab(customerId) {
      
      try {
        
        const isInFrame = this.validateCurrentWindowIsInFrame()
        
        if (isInFrame) {
          this.postCloseDialogMessage()
          return
        }
        
      } catch (error) {
        console.error(error)
      }
      
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);
    
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title,
      //   url,
      //   reload: true,
      //   close: true,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        reload: true,
        fromId
      })
    },
  },
  async mounted() {
    try {
      // 获取客户表单字段列表
      let result = await CustomerApi.getCustomerFields({isFromSetting: true});
      let synergiesField = result.data.find(v => v.fieldName === 'synergies')
      let setting = synergiesField?.setting
      if (setting) setting.max = 14
      
      if (result.data) {
        result.data.forEach(v => {
          if (v.fieldName === 'lmPhone') {
            v.isNull = 1
            v.placeholder = this.$t('customer.edit.inputPhonePlaceholder')
          }
          if (v.fieldName === 'lmEmail') {
            v.placeholder = this.$t('customer.edit.inputEmailPlaceholder')
          }
        })
      }
      if (result.succ) {
        this.fieldInfo = result.data;
      }
      // 权限数据
      this.auth = this.initData.auth || {}

      // 初始化默认值
      let form = {}
      if (this.initData.action === 'edit' && this.initData.id) {
        // 处理编辑时数据
        this.loadingPage = true
        let cusRes = await CustomerApi.getForEdit(this.initData.id)
        this.loadingPage = false
        if (cusRes.status === 0) form = cusRes.data
        if(this.registerId){
          let registerRes = await CustomerApi.getValue({id: this.registerId, customerId: this.initData.id});
          form = duibi(registerRes.data, form)
        }
      } else {
        // 检查版本数量限制
        this.checkNumExceedLimitBeforeHandler
        && this.checkNumExceedLimitBeforeHandler(
          TenantDataLimitSourceEnum.Customer,
          TenantDataLimitTypeEnum.Customer
        )
        if(this.registerId){
          let registerRes = await CustomerApi.getValue({id: this.registerId, customerId: this.initData.id});
          form = duibi(registerRes.data, form)
        }
      }
      // 从事件新建客户
      if (this.initData.action === 'createFromEvent') {
        form = this.initData.eventCustomer
      }

      // 处理富文本
      form = await FormUtil.initRichTextContent(this.fields, form);

      // 初始化解析表单数据
      form = util.packToForm(this.fields, form, this.initData.customerAddress)
      this.form = FormUtil.initialize(this.fields, form)
      query = parse(window.location.search) || {}
      if(query.lmPhone) {
        this.form.lmPhone = query.lmPhone
      }
      if(query.lmEmail) {
        this.form.lmEmail = query.lmEmail
      }
      this.init = true
      
      // 获取连接器新建数据
      // this.fetchConnectorInsertSelectCall()
      
    } catch (error) {
      this.toggleLoading(false)
      console.error('CustomerEditView mounted error ', error)
    }
  },
  beforeDestroy() {
    this.removeConnectorCreateSessionData()
  },
  components: {
    [CustomerEditForm.name]: CustomerEditForm,
    [PropagandaPage.name]: PropagandaPage,
    FormCellChange,
  }
}
</script>

<style lang="scss">
body {
  padding: 10px;
}

.customer-container {
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: #fff;
  border-radius: 4px;

  .page-title {
    border-bottom: 1px solid #f4f7f5;
    padding: 12px 10px;
    display: flex;
    justify-content: space-between;

    .iconfont {
      font-size: 12px;
    }

    .title {
      display: flex;
      justify-content: space-between;
      span.text {
        line-height: 34px;
        margin-right: 12px;
      }
    }
  }

  .base-form {
    height: 100%;
  }

  .form-builder-container {
    height: calc(100% - 56px);
    padding: 10px 16px;
    overflow: auto;
  }
  .form-builder-container-cell{
    padding: 24px 20px 24px 32px;
    .form-builder{
      padding: 0;
    }
  }
  .form-builder{
    .input-and-btn{
      display: flex !important;
      flex-flow: row nowrap;

      .form-item, .form-text, .form-select, .biz-team-select {
        flex: 1;
      }

      .base-dist-picker{
        padding-right: 0;
      }

      button{
        margin-left: 10px;
      }
    }
  }
  .propaganda-page-guide {
    margin-right: 15px;
  }
}

.in-frame-modal-view {
  
  overflow: hidden;
  
  .base-form {
    position: relative;
    height: 100%;
  }
  
  .fe-page-header,
  .page-title {
    position: fixed;
    right: 40px;
    bottom: 10px;
  }
  
  .form-builder {
    height: calc(100% - 60px);
    overflow-y: scroll;
    width: 100%;
    padding: 0 20px;
    margin-top: 0;
  }
  
  .base-form > .form-builder {
    
    padding-top: 20px;
    
    max-width: 100%;
    
  }
  
  .fe-page-header {
    
    top: inherit;
    
    .fe-page-header__left {
      display: none;
    }
    
  }
  
}
</style>
